package cn.mumzone.pos.ui.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import cn.mumzone.basic.adapter.rv.CommonAdapter;
import cn.mumzone.basic.adapter.rv.ViewHolder;
import cn.mumzone.basic.util.AppDateUtil;
import cn.mumzone.basic.util.ListUtil;
import cn.mumzone.basic.util.PosToast;
import cn.mumzone.basic.util.StringUtils;
import cn.mumzone.pos.R;
import cn.mumzone.pos.model.RepoGoodsEntity;
import cn.mumzone.pos.model.RepoGoodsSpecEntity;
import cn.mumzone.pos.model.RepoListGoodsEntity;
import cn.mumzone.pos.ui.fragment.FRA_StockIn;
import cn.mumzone.pos.ui.fragment.FRA_StockOut;
import cn.mumzone.pos.ui.widgets.keyboard.PosKeyBoardView;
import cn.mumzone.pos.ui.widgets.shopping.AnimShopButton;
import cn.mumzone.pos.ui.widgets.util.StringSpanUtils;
import cn.mumzone.pos.util.GoodsUtil;

/**
 * Created by qiuzhenhuan on 2019/7/31.
 * <p>
 * 出入库搜索结果列表适配器 && 列表展示，入库类型为「其他」时，适配器为 {@link ADA_CustomStockIn}
 */

public class ADA_StockInAndOut extends CommonAdapter<RepoListGoodsEntity> {

    private Context context;
    private boolean canDelete;
    private LayoutInflater mInflater;
    private int stockType;

    public ADA_StockInAndOut(Context context, int stockType, boolean canDelete) {
        super(context);
        this.context = context;
        this.canDelete = canDelete;
        this.stockType = stockType;
        mInflater = LayoutInflater.from(context);
    }

    @Override
    protected int itemLayoutId() {
        return R.layout.item_in_and_out_stock_list;
    }

    @Override
    protected void convert(final ViewHolder holder, final RepoListGoodsEntity repoGoodsEntity, final int position) {

        holder.setText(R.id.tv_good_name, StringUtils.get(repoGoodsEntity.getGoodsName()));
        holder.setText(R.id.tv_good_spec, getFormatGoodsSpec(repoGoodsEntity.getParameter()));

        if (canDelete) {
            // 盘点页面，可操作删除条目
            holder.setVisible(R.id.iv_delete, true);
            holder.setOnClickListener(R.id.iv_delete, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // 点击删除以后
                    if (mListener != null) {
                        mListener.OnClicked(position - 1, repoGoodsEntity);
                    }
                }
            });
        } else {
            holder.setVisible(R.id.iv_delete, false);
        }

        final LinearLayout llStorage = holder.getView(R.id.ll_storage_count);
        final LinearLayout llBatch = holder.getView(R.id.ll_batch_info);

        // 如果有批次信息
        if (!ListUtil.isListEmpty(repoGoodsEntity.getGoodsBatch())) {

            // 启用批次
            if (repoGoodsEntity.getIsBatch() == RepoListGoodsEntity.BATCH_ON) {
                llBatch.setVisibility(View.VISIBLE);
                llStorage.setVisibility(View.GONE);

                llBatch.removeAllViews();
                for (int i = 0; i < repoGoodsEntity.getGoodsBatch().size(); i++) {
                    final RepoGoodsEntity batchInfo = repoGoodsEntity.getGoodsBatch().get(i);

                    View batchInfoItem = mInflater.inflate(R.layout.item_stock_batch_goods, null);

                    ImageView ivDelete = batchInfoItem.findViewById(R.id.iv_delete);

                    TextView tvDate = batchInfoItem.findViewById(R.id.tv_production_date);
                    tvDate.setText(String.format("生产日期：%s", AppDateUtil.getDateToString(Long.valueOf(batchInfo.getDateInProduced()), AppDateUtil.YYYY_MM_DD2)));

                    TextView tvBatchNum = batchInfoItem.findViewById(R.id.tv_batch_number);
                    tvBatchNum.setText(String.format("批    次：%s", batchInfo.getGoodsBatchNumber()));

                    TextView tvStorage = batchInfoItem.findViewById(R.id.tv_storage);
                    tvStorage.setText(String.format("库存数量：%s%s", batchInfo.getGoodsQuantity(), batchInfo.getGoodsUnit()));
                    tvStorage.setVisibility(stockType == FRA_StockIn.STOCK_TYPE_IN ? View.INVISIBLE : View.VISIBLE);

                    TextView tvCountName = batchInfoItem.findViewById(R.id.tv_count_name);
                    tvCountName.setText(String.format("%s(%s):", getCountName(), batchInfo.getGoodsUnit()));

                    final AnimShopButton button = batchInfoItem.findViewById(R.id.v_modify_count);
                    // 结果页最小值为 1，搜索页最小值为 0
                    button.setMinCount(canDelete ? 1 : 0);
                    button.setMaxCount((stockType == FRA_StockIn.STOCK_TYPE_IN) ?
                            Integer.MAX_VALUE : Integer.parseInt(batchInfo.getGoodsQuantity()));
                    button.setCount(batchInfo.getSelectedCount());
                    button.setEnable(!batchInfo.isInTheInventory());

                    final int tag = i;
                    button.setOnAddDelListener(new GoodsStockButtonAdapter(mContext) {
                        @Override
                        protected void onAmountChanged(int count) {
                            batchInfo.setSelectedCount(count);
                            button.setCount(count);
                            if (mOnAmountChangeListener != null) {
                                mOnAmountChangeListener.onAmountChanged(count, tag, repoGoodsEntity);
                            }
                        }

                        @Override
                        public void onInputAreaClicked() {
                            GoodsUtil.showModifyCountDialog(mContext, new PosKeyBoardView.OnConfirmClickListener() {
                                @Override
                                public void onConfirmClick(String text) {
                                    // 出库设置数量，不能超过库存数量
                                    int inputCount = Integer.parseInt(text);
                                    if (stockType == FRA_StockOut.STOCK_TYPE_OUT) {
                                        if (inputCount > Integer.parseInt(batchInfo.getGoodsQuantity())) {
                                            PosToast.INSTANCE.makeShortToast(mContext, "出库数量不能大于库存数量~");
                                            return;
                                        }
                                    }
                                    batchInfo.setSelectedCount(inputCount);
                                    button.setCount(inputCount);
                                    notifyItemChanged(position - 1);
                                    if (mOnAmountChangeListener != null) {
                                        mOnAmountChangeListener.onAmountChanged(inputCount, -1, repoGoodsEntity);
                                    }
                                }
                            });
                        }
                    });

                    if (!canDelete) {
                        ivDelete.setVisibility(View.GONE);
                        llBatch.addView(batchInfoItem);
                        continue;
                    }

                    if (canDelete) {
                        ivDelete.setVisibility(View.VISIBLE);
                        ivDelete.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {

                                if (mOnBatchDeleteClickedListener != null) {
                                    mOnBatchDeleteClickedListener.onBatchDeleted(repoGoodsEntity, batchInfo);
                                }

                            }
                        });

                        if (batchInfo.getSelectedCount() > 0) {
                            llBatch.addView(batchInfoItem);
                        }
                    }

                }
            } else {
                llStorage.setVisibility(View.VISIBLE);
                llBatch.setVisibility(View.GONE);

                final RepoGoodsEntity entity = repoGoodsEntity.getGoodsBatch().get(0);

                TextView tvStorage = holder.getView(R.id.tv_storage);
                tvStorage.setText(String.format("库存数量：%s%s",
                        entity.getGoodsQuantity(), entity.getGoodsUnit()));
                tvStorage.setVisibility(stockType == FRA_StockIn.STOCK_TYPE_IN ? View.INVISIBLE : View.VISIBLE);

                holder.setText(R.id.tv_count_name, String.format("%s(%s):", getCountName(), entity.getGoodsUnit()));

                final AnimShopButton shopButton = holder.getView(R.id.v_modify_count);
                shopButton.setMinCount(canDelete ? 1 : 0); // 结果页最小值为 1，搜索页最小值为 0
                shopButton.setEnable(!repoGoodsEntity.isInTheInventory());
                shopButton.setCount(repoGoodsEntity.getSelectedCount());
                shopButton.setMaxCount((stockType == FRA_StockIn.STOCK_TYPE_IN) ?
                        Integer.MAX_VALUE : Integer.parseInt(entity.getGoodsQuantity()));

                shopButton.setOnAddDelListener(new GoodsStockButtonAdapter(mContext) {
                    @Override
                    protected void onAmountChanged(int count) {
                        repoGoodsEntity.setSelectedCount(count);
                        shopButton.setCount(count);
                        if (mOnAmountChangeListener != null) {
                            mOnAmountChangeListener.onAmountChanged(count, -1, repoGoodsEntity);
                        }
                    }

                    @Override
                    public void onInputAreaClicked() {
                        super.onInputAreaClicked();
                        GoodsUtil.showModifyCountDialog(mContext, new PosKeyBoardView.OnConfirmClickListener() {
                            @Override
                            public void onConfirmClick(String text) {
                                // 出库设置数量，不能超过库存数量
                                int inputCount = Integer.parseInt(text);
                                if (stockType == FRA_StockOut.STOCK_TYPE_OUT) {
                                    if (inputCount > Integer.parseInt(entity.getGoodsQuantity())) {
                                        PosToast.INSTANCE.makeShortToast(mContext, "出库数量不能大于库存数量~");
                                        return;
                                    }
                                }
                                repoGoodsEntity.setSelectedCount(inputCount);
                                shopButton.setCount(inputCount);
                                notifyItemChanged(position - 1);
                                if (mOnAmountChangeListener != null) {
                                    mOnAmountChangeListener.onAmountChanged(inputCount, -1, repoGoodsEntity);
                                }
                            }
                        });
                    }
                });


            }
        } else {
            llStorage.setVisibility(View.GONE);
            llBatch.setVisibility(View.GONE);
        }

    }

    private String getCountName() {
        if (stockType == FRA_StockOut.STOCK_TYPE_OUT) {
            return "出库数量";
        } else if (stockType == FRA_StockIn.STOCK_TYPE_IN) {
            return "入库数量";
        }
        return "数量";
    }

    private String getFormatGoodsSpec(List<RepoGoodsSpecEntity> goodsSpec) {
        StringBuilder builder = new StringBuilder();
        if (!ListUtil.isListEmpty(goodsSpec)) {
            for (int index = 0; index < goodsSpec.size(); index++) {
                RepoGoodsSpecEntity specBean = goodsSpec.get(index);
                builder.append(specBean.getParamValue());
                if (index < goodsSpec.size() - 1) {
                    builder.append("，");
                }
            }
        }
        return StringSpanUtils.init().addForegroundColorHighLight(mContext.getResources().getColor(R.color.weak_text_color), "规格：")
                .addStr(StringUtils.get(builder.toString(), "无")).build().toString();
    }

    public int getSelectedCount() {
        int totalCount = 0;
        outer: for (RepoListGoodsEntity entity : getDataList()) {
            if (entity.getIsBatch() == RepoListGoodsEntity.BATCH_ON) {
                for (RepoGoodsEntity batchEntity : entity.getGoodsBatch()) {
                    if (batchEntity.getSelectedCount() > 0) {
                        totalCount += 1;
                        continue outer;
                    }
                }
            } else {
                if (entity.getSelectedCount() > 0) {
                    totalCount += 1;
                }
            }
        }
        return totalCount;
    }

    public List<RepoListGoodsEntity> getSelectedData() {
        ArrayList<RepoListGoodsEntity> selectedList = new ArrayList<>();
        List<RepoListGoodsEntity> dataList = getDataList();
        outer: for (RepoListGoodsEntity entity : dataList) {
            if (entity.getIsBatch() == RepoListGoodsEntity.BATCH_ON) {
                for (RepoGoodsEntity batchEntity : entity.getGoodsBatch()) {
                    if (batchEntity.getSelectedCount() > 0) {
                        selectedList.add(entity);
                        continue outer;
                    }
                }
            } else {
                if (entity.getSelectedCount() > 0) {
                    selectedList.add(entity);
                }
            }
        }
        return selectedList;
    }

    public interface OnItemDeleteClickedListener {
        void OnClicked(int position, RepoListGoodsEntity repoGoodsEntity);
    }

    private OnItemDeleteClickedListener mListener;

    public void setOnItemDeleteClickedListener(OnItemDeleteClickedListener mListener) {
        this.mListener = mListener;
    }

    public interface OnBatchDeleteClickedListener {
        void onBatchDeleted(RepoListGoodsEntity currEntity, RepoGoodsEntity currBatch);
    }

    private OnBatchDeleteClickedListener mOnBatchDeleteClickedListener;

    public void setOnBatchDeletedListener(OnBatchDeleteClickedListener mListener) {
        this.mOnBatchDeleteClickedListener = mListener;
    }


    public interface OnAmountChangeListener {
        void onAmountChanged(int count, int tag, RepoListGoodsEntity currEntity);
    }

    private OnAmountChangeListener mOnAmountChangeListener;

    public void setOnAmountChangeListener(OnAmountChangeListener mListener) {
        this.mOnAmountChangeListener = mListener;
    }

}
